#pragma once

#include "sock.hpp"
#include <functional>
#include <sys/epoll.h>

namespace epoll_ns
{
    static const int defaultport = 8080;
    static const int size = 128;
    static const int defaultvalue = -1;
    static const int defaultnum = 64;

    using func_t = std::function<std::string(const std::string &)>;

    class EpollServer
    {
    public:
        EpollServer(func_t func, int num = defaultnum, uint16_t port = defaultport)
            : _func(func), _num(num), _revs(nullptr), _port(port), _listensock(defaultvalue), _epfd(defaultvalue)
        {
        }
        void initServer()
        {
            // 1. socket
            _listensock = Sock::Socket();
            Sock::Bind(_listensock, _port);
            Sock::Listen(_listensock);
            logMessage(NORMAL, "_listensock : %d", _listensock);

            // 2. epoll模型
            _epfd = epoll_create(size);
            if (_epfd < 0)
            {
                logMessage(FATAL, "epoll create error: %s", strerror(errno));
                exit(EPOLL_CREATE_ERR);
            }

            // 3. 添加listensock到epoll模型中
            struct epoll_event ev;
            ev.events = EPOLLIN;
            ev.data.fd = _listensock;
            epoll_ctl(_epfd, EPOLL_CTL_ADD, _listensock, &ev);

            // 4. 申请就绪事件的空间
            _revs = new struct epoll_event[_num];
        }
        void HandlerEvent(int readyNum)
        {
            logMessage(DEBUG, "HandlerEvent in");
            for (int i = 0; i < readyNum; ++i)
            {
                uint16_t events = _revs[i].events;
                int sock = _revs[i].data.fd;
                if (sock == _listensock && (events & EPOLLIN))
                {
                    // 获取新链接
                    std::string clientip;
                    uint16_t clientport;
                    int fd = Sock::Accept(sock, &clientip, &clientport);
                    if (fd < 0)
                    {
                        logMessage(WARNING, "accept error");
                        continue;
                    }
                    else
                    {
                        struct epoll_event ev;
                        ev.events = EPOLLIN;
                        ev.data.fd = fd;
                        epoll_ctl(_epfd, EPOLL_CTL_ADD, fd, &ev);
                    }
                }
                else if (events & EPOLLIN)
                {
                    // 普通读事件就绪
                    // 一定能读完吗? // 用while会不会被阻塞??
                    char buffer[1024];
                    int n = recv(sock, buffer, sizeof(buffer) - 1, 0);
                    if(n > 0)
                    {
                        // 正常读
                        buffer[n] = 0;
                        logMessage(DEBUG, "client# %s", buffer);
                        std::string request = _func(buffer);
                        send(sock, request.c_str(), request.size(), 0);
                    }
                    else if(n == 0)
                    {
                        // 需要先在内核删除对应的文件描述符
                        epoll_ctl(_epfd, EPOLL_CTL_DEL, sock, nullptr);
                        close(sock);
                        logMessage(NORMAL, "client quit!");
                    }
                    else
                    {
                        // 读出错
                        epoll_ctl(_epfd, EPOLL_CTL_DEL, sock, nullptr);
                        close(sock);
                        logMessage(ERROR, "Accept error, code: %d, errorstring: %s", errno, strerror(errno));
                    }
                }
                else
                {
                }
            }
            logMessage(DEBUG, "HandlerEvent in");
        }
        void start()
        {
            for (;;)
            {
                int timeout = 1000;
                int n = epoll_wait(_epfd, _revs, _num, timeout);
                switch (n)
                {
                case 0:
                    logMessage(NORMAL, "timeout...");
                    break;
                case -1:
                    logMessage(ERROR, "epoll_wait fail, code: %d, errstring: %s", errno, strerror(errno));
                    break;
                default:
                    logMessage(NORMAL, "have event ready");
                    HandlerEvent(n);
                    break;
                }
            }
        }
        ~EpollServer()
        {
            if (!_listensock != defaultvalue)
                close(_listensock);
            if (_epfd != defaultvalue)
                close(_epfd);
            if (_revs)
                delete[] _revs;
        }

    private:
        func_t _func;
        uint16_t _port;
        int _listensock;
        int _epfd;
        struct epoll_event *_revs;
        int _num;
    };
}